﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Text.Json;

namespace DevBox
{
    public static class JsonSerializerExtension
    {

        /// <summary>
        /// 序列化为Json字符串
        /// </summary>
        public static string ToJson(this object item, JsonSerializerOptions? settings = null)
        {
            return JsonSerializer.Serialize(item, settings);
        }

        /// <summary>
        /// 序列化为缩进Json字符串
        /// </summary>
        public static string ToIndentedJson(this object item, JsonSerializerOptions? settings = null)
        {
            if (settings == null)
            {
                settings = new JsonSerializerOptions
                {
                    WriteIndented = true,
                };
            }
            return JsonSerializer.Serialize(item, settings);
        }

        /// <summary>
        /// Json字符串反序列化对象
        /// </summary>
        public static T FromJsonToObj<T>(this string jsonString, JsonSerializerOptions? settings = null)
        {
           return JsonSerializer.Deserialize<T>(jsonString, settings);
        }
    }
}
